import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import { Row, Col, Card, Form, Input, Select, Button } from 'antd';
import StandardTable from '@/components/StandardTable';
import EventDetails from './EventDetails';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import SearchSelect from '@/components/SearchSelect';
import { codes, Status, EventType, NoticeMode, formatStatus } from './utils';
import AdSelect from '@/components/AdSelect';
import AdSearch from '@/components/AdSearch';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ events, common, component, loading }) => ({
  events,
  loading: loading.effects['events/eventsList'],
  dictObject: common.dictObject,
  searchValue: component.searchValue,
}))
@Form.create()
export default class EventsList extends Component {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    stepFormValues: {},
    visible: false,
    rechargeVisible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    isAbled: '',
    rowDetails: {},
  };
  className = 'eventList';

  columns = [
    {
      title: '事件代码',
      dataIndex: 'eventCode',
      render: (text, record) => (
        <a onClick={e => this.showDetail(e, record)} title={text}>
          {text}
        </a>
      ),
      width: 200,
    },
    {
      title: '事件名称',
      dataIndex: 'eventName',
      render: text => <span title={text}>{text}</span>,
      width: 200,
    },
    {
      title: '模板内容',
      dataIndex: 'content',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '状态',
      dataIndex: 'beActive',
      render: text => <span>{formatStatus(text)}</span>,
      width: 100,
    },
    {
      title: '是否使用规则',
      dataIndex: 'beUseRule',
      render: text => <span>{text ? '是' : '否'}</span>,
      width: 100,
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      render: text => <AdSelect data={EventType} value={text} onlyRead={true} />,
    },
    {
      title: '通知方式',
      dataIndex: 'noticeMode',
      render: text => <AdSelect data={NoticeMode} value={text} onlyRead={true} />,
    },
    {
      title: '发送方',
      dataIndex: 'senderId',
      render: text => (
        <AdSearch
          label="accountNo"
          name="accountName"
          title={text}
          value={this.props.searchValue[text] ? [this.props.searchValue[text]] : []}
          onlyRead={true}
        />
      ),
    },
  ];
  componentDidMount() {
    this.getEventList();
  }

  getEventList = (params = {}) => {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: 'events/eventsList',
      payload: params,
      callback: data => {
        if (!data) return;
        let valueList = [];
        data.map(v => {
          const labels = ['senderId'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: {
                    params: { id: v[item] },
                    url: 'sms/sms-sender/viewSmsSenderDetails',
                    // params: { accountNo: v[item] },
                    // url:'sms/sms-sender/selectSmsSenderList', //查询列表接口，返回数组数据
                  },
                });
            }
          });
        });
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getEventList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { ...value } = values;
    this.setState({
      formValues: value,
    });
    this.getEventList(value);
  };

  //新建
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push(`/manageMsg/eventList/eventAdd`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/manageMsg/eventList/eventEdit/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.getEventList(params);
  };

  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id } = record;
    // console.log('senderId', record.senderId);

    dispatch({
      type: 'events/eventsDetails',
      payload: { id },
      callback: res => {
        this.setState({
          isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
        });
      },
    });
    dispatch({
      type: 'events/eventReceiverList',
      payload: { id, pageSize: 500 },
    });

    this.setState(
      {
        checkId: id,
        rowDetails: record,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };

  //启用、禁用：
  abledStatus = (type, isSingle) => {
    const { dispatch } = this.props;
    const { checkIds, checkId, formValues } = this.state;
    let params = {};
    params.ids = isSingle ? [checkId] : checkIds;
    params.type = type == 'abled' ? true : false;
    dispatch({
      type: 'events/ableOperate',
      payload: params,
      callback: res => {
        this.getEventList(formValues);

        if (isSingle) {
          this.props.dispatch({
            type: 'events/eventsDetails',
            payload: { id: checkId },
            callback: res => {
              this.setState({
                isAbled: res.beActive == true || res.beActive == '启用' ? true : false,
              });
            },
          });
        }
      },
    });
  };
  handleCancel = e => {
    this.setState({
      rechargeVisible: false,
    });
  };
  handleRechargeOK = () => {
    this.child.operatePaneButton();
  };
  getChildValue = data => {
    if (data == 'false') {
      this.handleCancel();
    }
  };
  render() {
    const {
      loading,
      events: { eventsList, eventsDetails },
      form,
      isMobile,
      dictObject,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      selectedRows,
      updateModalVisible,
      stepFormValues,
      isAbled,
      checkId,
      visible,
      rechargeVisible,
      rowDetails,
      expandForm,
    } = this.state;

    const selectDetails = eventsDetails[checkId];
    const firstFormItem = (
      <FormItem label="事件代码">
        {getFieldDecorator('eventCode')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="事件名称">
        {getFieldDecorator('eventName')(<Input placeholder="请输入" />)}
      </FormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="状态">
          {getFieldDecorator('beActive')(
            <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
              <Option value="">请选择</Option>
              {Status.map(v => {
                return <Option value={v.code}>{v.value}</Option>;
              })}
            </Select>
          )}
        </FormItem>,
      ],
      [
        <FormItem label="事件类型">
          {getFieldDecorator('eventType')(
            <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
              <Option value="">请选择</Option>
              {EventType.map(v => {
                return <Option value={v.code}>{v.value}</Option>;
              })}
            </Select>
          )}
        </FormItem>,
        <FormItem label="通知方式">
          {getFieldDecorator('noticeMode')(
            <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
              <Option value="">请选择</Option>
              {NoticeMode.map(v => {
                return <Option value={v.code}>{v.value}</Option>;
              })}
            </Select>
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      buttons: (
        <Button.Group>
          <Button
            onClick={() => this.abledStatus('disabled')}
            disabled={selectedRows.length > 0 ? false : true}
          >
            禁用
          </Button>
          <Button
            onClick={() => this.abledStatus('abled')}
            disabled={selectedRows.length > 0 ? false : true}
          >
            启用
          </Button>
        </Button.Group>
      ),
      selectedRows: selectedRows,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '事件详情',
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <Button.Group>
            {!isAbled && <Button onClick={() => this.abledStatus('abled', 1)}>启用</Button>}
            {isAbled && <Button onClick={() => this.abledStatus('disabled', 1)}>禁用</Button>}
            <Button type="primary" onClick={this.handleEdit}>
              编辑
            </Button>
          </Button.Group>
        </span>
      ),
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={eventsList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          // scrollX={1000}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <EventDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
      </Fragment>
    );
  }
}
